/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.celularessuc.gco.ui;

import com.jjsoft.celularessuc.gco.mdl.Gasto;
import com.jjsoft.celularessuc.gco.mdl.Ingreso;
import com.jjsoft.celularessuc.gco.mdl.Usuario;
import com.jjsoft.celularessuc.gco.neg.DiarioManager;
import com.jjsoft.celularessuc.gco.neg.GastoManager;
import com.jjsoft.celularessuc.gco.neg.IngresoManager;
import com.jjsoft.celularessuc.gco.neg.UsuarioManager;
import com.jjsoft.celularessuc.gco.util.CNumeros;
import com.jjsoft.celularessuc.gco.util.MiModelo;
import com.jjsoft.celularessuc.gco.util.configuraciones;
import java.util.Date;
import java.util.List;

/**
 *
 * @author Johnny
 */
public class VVerCajaUsuario extends javax.swing.JFrame {

    /**
     * Creates new form VVerCajaUsuario
     */
    IngresoManager im = new IngresoManager();
    GastoManager gm = new GastoManager();
    DiarioManager dm = new DiarioManager();
    MiModelo modeloIngresos = new MiModelo();
    MiModelo modeloEgresos = new MiModelo();
    private static VVerCajaUsuario instance;
            List<Usuario> listaUsuarios = null;


    private VVerCajaUsuario() {
        initComponents();
        dtFechaInicio.setDate(new Date());
        UsuarioManager um = new UsuarioManager();
        listaUsuarios = um.listaUsuarios();
        for (int i = 0; i < listaUsuarios.size(); i++) {
            cboUsuarios.addItem(listaUsuarios.get(i).getNick());
        }
        cboUsuarios.setSelectedIndex(0);


    }

    public static VVerCajaUsuario getInstance() {
        if (instance == null) {
            instance = new VVerCajaUsuario();
        }
        return instance;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgEgresos = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        dtgIngresos = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        txtTotalIngresos = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtTotalCaja = new javax.swing.JTextField();
        txtTotalEgresos = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        cboUsuarios = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        dtFechaInicio = new com.toedter.calendar.JDateChooser();
        cmdVer = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("CAJA DIARIA");

        jLabel2.setText("INGRESOS");

        dtgEgresos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(dtgEgresos);

        dtgIngresos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(dtgIngresos);

        jButton1.setText("Aceptar");

        jLabel4.setText("Total:");

        txtTotalIngresos.setEditable(false);

        jLabel6.setText("Total Caja:");

        jLabel5.setText("Total:");

        jLabel7.setText("Usuario:");

        jLabel8.setText("Fecha:");

        dtFechaInicio.setDateFormatString("yyyy-MM-dd");

        cmdVer.setText("Ver");
        cmdVer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdVerActionPerformed(evt);
            }
        });

        jLabel9.setText("EGRESOS");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtTotalIngresos, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jButton1)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel5))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtTotalEgresos, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtTotalCaja, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cboUsuarios, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(dtFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cmdVer)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel9)
                                .addGap(222, 222, 222))))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(300, 300, 300))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel7)
                        .addComponent(cboUsuarios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel8))
                    .addComponent(dtFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdVer))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(txtTotalEgresos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtTotalIngresos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtTotalCaja, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(990, 449));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void cmdVerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdVerActionPerformed
        // TODO add your handling code here:
        modeloEgresos = new MiModelo();
        modeloIngresos = new MiModelo();
        cargarIngresos();
        cargarEgresos();
        cargarTotal();
    }//GEN-LAST:event_cmdVerActionPerformed
    private void cargarIngresos() {
        String[] cabeceras = new String[]{"Fecha", "Hora", "Concepto","Documento", "Valor"};
        modeloIngresos.setColumnIdentifiers(cabeceras);
        dtgIngresos.setModel(modeloIngresos);
        dtgIngresos.getColumn("Concepto").setPreferredWidth(160);
        dtgIngresos.getColumn("Fecha").setPreferredWidth(70);
        dtgIngresos.getColumn("Hora").setPreferredWidth(40);
        Date d = dtFechaInicio.getDate();
        List<Ingreso> listaIngresos = im.listarIngresos(d, listaUsuarios.get(cboUsuarios.getSelectedIndex()));
        double total = 0;
        if (listaIngresos != null) {

        for(int i = 0; i<listaIngresos.size();i++)
        {
            String fechaIng=listaIngresos.get(i).getFecha().toLocaleString().split(" ")[0];
            String documento="";
            if(listaIngresos.get(i).getNumDocumento()!=null)
            {
                documento=listaIngresos.get(i).getNumDocumento().toString();
            }
            String []datos = new String[]{fechaIng, listaIngresos.get(i).getHora(),listaIngresos.get(i).getConcepto(),documento,String.valueOf(CNumeros.redondear(listaIngresos.get(i).getValor()))};
            modeloIngresos.addRow(datos);
            total=total+listaIngresos.get(i).getValor();
        }
        txtTotalIngresos.setText(String.valueOf(redondear(total)));
        }
        
    }

    private void cargarEgresos() {
        String[] cabeceras = new String[]{"Fecha", "Hora", "Concepto", "Valor"};
        modeloEgresos.setColumnIdentifiers(cabeceras);
        dtgEgresos.setModel(modeloEgresos);
        dtgEgresos.getColumn("Concepto").setPreferredWidth(180);
        dtgEgresos.getColumn("Fecha").setPreferredWidth(70);
        dtgEgresos.getColumn("Hora").setPreferredWidth(40);
        Date d = dtFechaInicio.getDate();
        String fecha = (d.getYear() + 1900) + "-" + (d.getMonth() + 1) + "-" + d.getDate();
        List<Gasto> listaEgresos = gm.listarGastos(d, configuraciones.getInstance().getUsuario());
        double total = 0;
        if(listaEgresos!=null)
        {
        for (int i = 0; i < listaEgresos.size(); i++) {
            String fechaEg = listaEgresos.get(i).getFecha().getDate() + "/" + (listaEgresos.get(i).getFecha().getMonth() + 1) + "/" + (listaEgresos.get(i).getFecha().getYear() + 1900);
            String[] datos = new String[]{fechaEg, listaEgresos.get(i).getHora(), listaEgresos.get(i).getConcepto(), String.valueOf(listaEgresos.get(i).getValor())};
            modeloEgresos.addRow(datos);
            total = total + listaEgresos.get(i).getValor();
        }
        txtTotalEgresos.setText(String.valueOf(redondear(total)));
        }
    }

    private void cargarTotal() {
        txtTotalCaja.setText(String.valueOf(redondear(Double.parseDouble(txtTotalIngresos.getText()) - Double.parseDouble(txtTotalEgresos.getText()))));
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VVerCajaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VVerCajaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VVerCajaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VVerCajaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VVerCajaUsuario().setVisible(true);
            }
        });
    }

    private double redondear(double num) {
        num = num * 100d;
        num = Math.round(num);
        int numr = (int) num;
        return (double) numr / 100d;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cboUsuarios;
    private javax.swing.JButton cmdVer;
    private com.toedter.calendar.JDateChooser dtFechaInicio;
    private javax.swing.JTable dtgEgresos;
    private javax.swing.JTable dtgIngresos;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField txtTotalCaja;
    private javax.swing.JTextField txtTotalEgresos;
    private javax.swing.JTextField txtTotalIngresos;
    // End of variables declaration//GEN-END:variables
}
